//
//  GMArtListViewController.h
//  gentleman
//
//  Created by 范月成 on 2017/12/5.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMArtListViewController.h"
#import "GMArtListModel.h"
#import "GMPlaceHolderView.h"
#import "GMSkeletonView.h"
#import "GMTouchIDViewController.h"

@interface GMArtListViewController () <UISearchBarDelegate>

@property (nonatomic, assign, readwrite) GMArtListType type;

@property (nonatomic, strong) GMArtListModel *listModel;
@property (nonatomic, strong) GMSkeletonDataSourceProvider *provider;
@property (nonatomic, strong) UITableView *artworksList;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) GMPlaceHolderView *artworksEmpty;

@end

@implementation GMArtListViewController

+ (void)load {
    [MGJRouter registerURLPattern:kRouterArtworkList
                        toHandler:^(NSDictionary *routerParameters) {
                            GMArtListType type = [routerParameters[@"type"] integerValue];
                            NSString *keyword = routerParameters[@"keyword"];
      
                            GMArtListViewController *artworkDetail = [[GMArtListViewController alloc] initWithType:type];
                            artworkDetail.hidesBottomBarWhenPushed = YES;
                            if (type == GMArtListTypeSearch) {
                                NSNumber *hidden = routerParameters[MGJRouterParameterUserInfo][@"hidden"];
                                artworkDetail.searchBarHidden = [hidden boolValue];
                            }
        
                            artworkDetail.keyword = keyword;
                            [[UIViewController currentNavigationViewController] pushViewController:artworkDetail animated:YES];
                        }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init {
    if (self = [super init]) {
        self.type = GMArtListTypeHomePage;
    }
    return self;
}

- (instancetype)initWithType:(GMArtListType)type {
    if (self = [super init]) {
        self.type = type;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    BOOL shouldRequestData = NO;
    if (self.type == GMArtListTypeSearch) {
        shouldRequestData = self.keyword.length && !self.listModel.listDatas.count;
    } else {
        shouldRequestData = !self.listModel.listDatas.count;
    }
    !shouldRequestData?:[self requestDatas];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    kAdjustsScrollViewInsets_NO(self.artworksList, self);
    
    [self setNavigationTitle];
    
    if (self.type == GMArtListTypeSearch && !self.searchBarHidden) {
        UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        spacer.width = -15;
        UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:self.searchBar];
        self.searchBar.text = self.keyword;
        self.navigationItem.leftBarButtonItems = @[spacer, left];
    }
    
    if (self.type == GMArtListTypeSearch) {
        self.artworksList.dataSource = self.listModel;
        self.artworksList.delegate = self.listModel;
        self.artworksEmpty.hidden = NO;
    } else {
        self.artworksList.dataSource = self.provider;
        self.artworksList.delegate = self.provider;
        self.artworksEmpty.hidden = YES;
        [self.artworksList reloadData];
    }
    
    if (self.type == GMArtListTypeHomePage) {
        if ([UserDefaultsForKey(@"GentleMode") boolValue]) {
            if ([[GMProtectTool shareTool] isEnableTouchID]) {
                GMTouchIDViewController *touchID = [GMTouchIDViewController new];
                [self presentViewController:touchID
                                   animated:nil completion:nil];
            }
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestDatas) name:kNotificationReloadList object:nil];
}

- (void)setNavigationTitle {
    NSString *navigationTitle = nil;
    switch (self.type) {
        case GMArtListTypeHomePage:
            navigationTitle = @"首页";
            break;
        case GMArtListTypeTag:
            navigationTitle = [[self.keyword componentsSeparatedByString:@":"][1] stringByReplacingOccurrencesOfString:@"+" withString:@" "];
            break;
         
        case GMArtListTypeUploader:
        case GMArtListTypeCategory:
        case GMArtListTypeLiked:
        case GMArtListTypeDownload:
            navigationTitle = self.keyword;
            break;
        default:
            break;
    }
    self.navigationItem.title = navigationTitle;
}

- (void)initSubviews {
    [super initSubviews];
    [self.view addSubview:self.artworksList];
}

- (void)requestDatas {
    self.artworksList.scrollEnabled = NO;
    switch (self.type) {
        case GMArtListTypeHomePage:{
            [self.listModel getHomePageListDatas:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeSearch:{
            [self.listModel getSearchListDatasWithKey:self.searchBar.text completed:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeTag:{
            [self.listModel getTagListDatas:self.keyword completed:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeCategory:{
            [self.listModel getCategoryListDatas:self.keyword completed:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeUploader:{
            [self.listModel getUploaderListDatas:self.keyword completed:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        case GMArtListTypeLiked:{
            [self.listModel getLocalLikeListDatas:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        case GMArtListTypeDownload:{
            [self.listModel getLocalDownloadListDatas:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        default:
            break;
    }
}

- (void)requestNextPage {
    switch (self.type) {
        case GMArtListTypeHomePage:{
            [self.listModel getHomePageListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeSearch:{
            [self.listModel getSearchListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeTag:{
            [self.listModel getTagListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeCategory:{
            [self.listModel getCategoryListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
            
        case GMArtListTypeUploader:{
            [self.listModel getUploaderListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        case GMArtListTypeLiked:{
            [self.listModel getLocalLikeListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        case GMArtListTypeDownload:{
            [self.listModel getLocalDownloadListNext:^(NSError *error, NSMutableArray *list) {
                [self reloadDatasWithError:error];
            }];
            break;}
        default:
            break;
    }
}

- (void)reloadDatasWithError:(NSError *)error {
    if (error) {
        if (![XMCenter isNetworkReachable]) {
            self.artworksEmpty.title = @"网络异常";
        } else {
            self.artworksEmpty.title = error.domain;
            !(error.code == 444)?:[self.artworksList.mj_footer endRefreshingWithNoMoreData];
        }
    } else {
        !(self.listModel.page == 1)?:[self.artworksList.mj_footer resetNoMoreData];
    }
    self.artworksEmpty.hidden = NO;
    self.artworksList.scrollEnabled = YES;
    
    if (self.artworksList.dataSource != self.listModel || self.artworksList.delegate != self.listModel) {
        self.artworksList.dataSource = self.listModel;
        self.artworksList.delegate = self.listModel;
    }
    
    [self.artworksList.mj_header endRefreshing];
    [self.artworksList.mj_footer endRefreshing];
    [self.artworksList reloadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.artworksList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(self.safeAreaTop);
        make.left.equalTo(self.view);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(kScreenHeight-self.safeAreaTop-self.safeAreaBottom);
    }];
}

#pragma mark - search
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:NO animated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self requestDatas];
}

#pragma mark - getter
- (GMArtListModel *)listModel {
    if (!_listModel) {
        _listModel = [[GMArtListModel alloc] init];
        _listModel.isDownloadList = (self.type == GMArtListTypeDownload);
    }
    return _listModel;
}

- (UITableView *)artworksList {
    if (!_artworksList) {
        _artworksList = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _artworksList.tableFooterView = [UIView new];
        [_artworksList disabledEstimatedHeight];
        _artworksList.rowHeight = 44*3;
        [_artworksList registerClass:NSClassFromString(@"GMArtworkListCell") forCellReuseIdentifier:@"GMArtworkListCell"];
        
        @weakify(self)
        _artworksList.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            [self requestDatas];
        }];
        
        _artworksList.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self requestNextPage];
        }];
        
        [_artworksList gm_configureWithPlaceHolderBlock:^UIView * _Nonnull(UITableView * _Nonnull sender) {
            @strongify(self)
            return self.artworksEmpty;
        } normalBlock:nil];
    }
    return _artworksList;
}

- (GMPlaceHolderView *)artworksEmpty {
    if (!_artworksEmpty) {
        _artworksEmpty = [[GMPlaceHolderView alloc] initWithFrame:self.artworksList.bounds];
        _artworksEmpty.title = @"木有数据";
        @weakify(self)
        _artworksEmpty.refreshBlock = ^{
            @strongify(self)
            [self requestDatas];
        };
    }
    return _artworksEmpty;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.transform = CGAffineTransformMakeScale(0.9, 0.9);
        _searchBar.delegate = self;
        _searchBar.returnKeyType = UIReturnKeySearch;
        _searchBar.frame = CGRectMake(0, 0, kScreenWidth-20, 44);
        _searchBar.placeholder = @"输入关键词";
    }
    return _searchBar;
}

- (GMSkeletonDataSourceProvider *)provider {
    if (!_provider) {
        _provider = [GMSkeletonDataSourceProvider dataSourceProviderWithCellReuseIdentifier:@"GMArtworkListCell"];
    }
    return _provider;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
